﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using ComicIsland.Common.StorageHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using RestSharp;
using WeiboSdk;

namespace ComicIsland.App.Controls
{
    public partial class SharedContentPage : PhoneApplicationPage
    {
        private const string shareImagePath = "comicShareImage.png";
        private ShareData shareData;
        public SharedContentPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string tmpShareData;
            base.NavigationContext.QueryString.TryGetValue("json", out tmpShareData);
            if (string.IsNullOrWhiteSpace(tmpShareData))
            {
                this.NavigationService.GoBack();
                return;
            }
            this.shareData = JSONHelper.Deserialize<ShareData>(tmpShareData);
            if (!(shareData != null && !string.IsNullOrWhiteSpace(shareData.Content)))
            {
                this.NavigationService.GoBack();
                return;
            }
            this.tbContent.Text = this.shareData.Content;
            //BitmapImage bi = new BitmapImage(new Uri(this.shareData.ImageUrl, UriKind.Relative));
            LoadSharedImage();
            //
            base.OnNavigatedTo(e);
        }

        void LoadSharedImage()
        {
            //
            if ((int)ImageLocationType.AppFile == this.shareData.ImageSavedType || (int)ImageLocationType.Net == this.shareData.ImageSavedType)
            {
                if ((int)ImageLocationType.AppFile == this.shareData.ImageSavedType)
                    this.image.Source = new BitmapImage(new Uri(this.shareData.ImageUrl, UriKind.Relative));
                else if ((int)ImageLocationType.Net == this.shareData.ImageSavedType)
                    this.image.Source = new BitmapImage(new Uri(this.shareData.ImageUrl, UriKind.Absolute));                
            }
            else if ((int)ImageLocationType.Iso == this.shareData.ImageSavedType)
            {
                try
                {
                    using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (IsolatedStorageFileStream isoStream = store.OpenFile(this.shareData.ImageUrl, FileMode.Open))
                        {
                            MemoryStream stream = new MemoryStream();
                            isoStream.CopyTo(stream);
                            isoStream.Close();
                            isoStream.Dispose();
                            store.Dispose();
                            var bitmapImage = new BitmapImage();
                            bitmapImage.SetSource(stream);
                            this.image.Source = bitmapImage;
                            this.psbStatus.CloseStatusBar();
                            //
                            //this.shareData.ImageByte = stream.ToArray();
                        }
                    }
                }
                catch { }
            }
            this.image.Loaded += image_Loaded;
            this.image.ImageFailed += image_ImageFailed;
        }

        void image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            this.psbStatus.CloseStatusBar();
            MessageToastManager.Show("加载资源失败！");
        }

        void image_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                WriteableBitmap writeableBitmap = new WriteableBitmap(this.image.Source as BitmapSource);
                using (var isfile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (isfile.FileExists(shareImagePath))
                    {
                        isfile.DeleteFile(shareImagePath);
                    }
                    using (IsolatedStorageFileStream fs = isfile.CreateFile(shareImagePath))
                    {
                        System.Windows.Media.Imaging.Extensions.SaveJpeg(writeableBitmap, fs, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);
                    }
                    using (MemoryStream stream = new MemoryStream())
                    {
                        writeableBitmap.SaveJpeg(stream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);
                        this.shareData.ImageByte = stream.ToArray();
                    }
                    LogHelper.LogInfo("图片已下载，可进行分享操作！");
                }
            }
            catch
            {
            }
            finally
            {
                this.psbStatus.CloseStatusBar();
            }
        }



        private void appBarConfirm_Click(object sender, EventArgs e)
        {
            if (ShareType.SinaWeibo.ToString().Equals(this.shareData.ShareType))
            {
                SendSinaWeibo();
            }
            else if (ShareType.QQWeibo.ToString().Equals(this.shareData.ShareType))
            {
                if (this.shareData.ImageByte != null && this.shareData.ImageByte.Length > 0)
                {
                    SendImageToQQWeibo();
                }
                else
                {
                    MessageToastManager.Show("分享图片不存在，请重试！");
                }
            }
            else
            {
                MessageToastManager.Show("分享失败，请重试！");
                if (NavigationService.CanGoBack)
                    NavigationService.GoBack();
            }
        }

        #region 新浪微博
        void SendSinaWeibo()
        {
            this.psbStatus.OpenStatusBar("正在分享...");
            SdkNetEngine netEngine = new SdkNetEngine();
            cmdUploadPic cmdBase = new cmdUploadPic
            {
                messageText = this.tbContent.Text,
                picPath = shareImagePath,
                acessToken = this.shareData.AccessToken
            };
            netEngine.RequestCmd(SdkRequestType.UPLOAD_MESSAGE_PIC, cmdBase, sinaWeiboRequestCompleted);
        }

        void sinaWeiboRequestCompleted(SdkRequestType requestType, SdkResponse response)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                this.psbStatus.CloseStatusBar();
                if (SdkErrCode.SUCCESS == response.errCode)
                {
                    MessageToastManager.Show("分享成功！");
                    if (NavigationService.CanGoBack)
                        NavigationService.GoBack();
                }
                else
                {
                    MessageToastManager.Show("分享失败，请重试！");
                }
            });
        }
        #endregion 新浪微博

        void SendImageToQQWeibo()
        {
            this.psbStatus.OpenStatusBar("正在分享...");
            var request = new RestRequest(Method.POST);
            request.RequestFormat = DataFormat.Json;
            var boundary = string.Concat("--", DateTime.Now.Ticks);
            request.AddHeader("Content-Type", string.Concat("multipart/form-data; boundary=", boundary));
            request.Resource = "t/add_pic_t";
            request.AddParameter("content", this.tbContent.Text.Trim());
            request.AddFile("pic", this.shareData.ImageByte, shareImagePath);
            request.AddParameter("access_token", this.shareData.AccessToken);
            request.AddParameter("oauth_consumer_key", this.shareData.AppKey);
            request.AddParameter("openid", this.shareData.OpenId);
            RestClient restClient = new RestClient(new Uri("https://graph.qq.com", UriKind.Absolute));
            restClient.ExecuteAsync(request, (response) =>
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    this.psbStatus.CloseStatusBar();
                });
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    MessageToastManager.Show("分享失败，请重试！");
                }
                else
                {
                    LogHelper.LogInfo(response.Content, this.GetType(), MethodBase.GetCurrentMethod());
                    var result = JSONHelper.Deserialize<ShareQQWeiboResult>(response.Content);
                    if (result != null && result.Ret == 0)
                    {
                        MessageToastManager.Show("分享成功！");
                        if (NavigationService.CanGoBack)
                            NavigationService.GoBack();
                    }
                    else
                    {
                        MessageToastManager.Show("分享失败，请重试！");
                    }
                }
            });
        }

        /// <summary>
        /// 发表纯文字QQ微博
        /// </summary>
        void SendTextToQQWeibo()
        {
            var request = new RestRequest(Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.Resource = "t/add_t";
            request.AddParameter("content", this.tbContent.Text.Trim());
            //if (!string.IsNullOrEmpty(clientip))
            //{
            //    request.AddParameter("clientip", clientip);
            //}
            //if (!string.IsNullOrEmpty(jing))
            //{
            //    request.AddParameter("jing", jing);
            //}
            //if (!string.IsNullOrEmpty(wei))
            //{
            //    request.AddParameter("wei", wei);
            //}
            request.AddParameter("syncflag", 0);

            //
            request.AddParameter("access_token", this.shareData.AccessToken);
            request.AddParameter("oauth_consumer_key", this.shareData.AppKey);
            request.AddParameter("openid", this.shareData.OpenId);
            RestClient restClient = new RestClient(new Uri("https://graph.qq.com", UriKind.Absolute));
            restClient.ExecuteAsync(request, (response) =>
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    MessageToastManager.Show("分享失败，请重试！");
                }
                else
                {
                    LogHelper.LogInfo(response.Content, this.GetType(), MethodBase.GetCurrentMethod());
                    var result = JSONHelper.Deserialize<ShareQQWeiboResult>(response.Content);
                    if (result != null && result.Ret == 0)
                    {
                        MessageToastManager.Show("分享成功！");
                        if (NavigationService.CanGoBack)
                            NavigationService.GoBack();
                    }
                    else
                    {
                        MessageToastManager.Show("分享失败，请重试！");
                    }
                }
            });
        }

    }
}